<?php
/**
 * 微信小程序 推送发货
 */

class Weshop
{
    private $appid = 'wx6e025202dd00d3c1';
    private $appsecret = 'a4ae1ac7d2722064f63fcc56a4388164';

    /**
     * 推送发货信息
     *
     * @param [type] $data
     * @return void
     */
    public function push($data)
    {
        // $data = [
        //     'logistics_type' => 3,
        //     'openid' => 'oRGh46yQ8UxqMN6YT6Tw-ARL48xQ',
        //     'trade_no' => '42000020112023101459125794062',
        //     'item_desc' => '虚拟发货',
        //     'delivery_id' => '1111',
        //     'delivery_code' => 'ZTO',
        // ];
        //参考文档 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html#%E4%B8%80%E3%80%81%E5%8F%91%E8%B4%A7%E4%BF%A1%E6%81%AF%E5%BD%95%E5%85%A5%E6%8E%A5%E5%8F%A3
        $arr = array(
            'order_key' => array(
                'order_number_type' => 2,
                'transaction_id' => $data['trade_no'] ?? '', //微信交易单号  420000202020231128889459505
            ),
            'logistics_type' => $data['logistics_type'] ?? 1, //物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
            'delivery_mode' => 1, //发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）2、SPLIT_DELIVERY（分拆发货） 示例值: UNIFIED_DELIVERY
            'shipping_list' => array(
                array(
                    'tracking_no' => $data['delivery_id'] ?? '', //物流单号
                    'express_company' => $data['delivery_code'] ?? '', //物流公司编码
                    'item_desc' => $data['item_desc'] ?? '', //商品信息：商品名称*数量
                )
            ),
            'upload_time' => date('c'), //输出值：2022-12-15T13:29:35+08:00
            'payer' => array(
                'openid' => $data['openid'] ?? '',

            )
        );
        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' . $this->getAccessToken();
        $res = $this->curl_post($url, $arr);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            $msg = $res['errcode'] . $res['errmsg'];
            throw new Exception($msg);
        }
        return $res;
    }

    /**
     * 获取access_token
     *
     * @return void
     */
    public function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        $response = file_get_contents($url);
        $result = json_decode($response, true);
        if (isset($result['access_token'])) {
            return $result['access_token'];
        } else {
            throw new Exception("access_token获取失败");
        }
    }

    /*
    * crur post请求
    *
    * @param [type] $url
    * @param [type] $post_data
    * @return void
    */
    public function curl_post($url, $post_data)
    {
        // 发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        // 第二个参数为true，表示格式化输出json
        $data = json_decode($result, true);
        return $data;
    }
}
